﻿using System.IO.IsolatedStorage;
using System.Windows;

using DanielVaughan.ComponentModel;

using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace DanielVaughan.Services.Implementation
{
	/* TODO: [DV] Comment. */
	public class LockScreenService : ObservableObject, ILockScreenService
	{
		static readonly string promptedKey = "UserPromptedToAllowRunningUnderLockScreen";
		static readonly string runningEnabledKey = "RunningUnderLockScreenEnabled";

		public static string RunningEnabledSettingsKey
		{
			get
			{
				return runningEnabledKey;
			}
		}

		public LockScreenService()
		{
			var settingsService = Dependency.Resolve<ISettingsService, SettingsService>();
			
			if (settingsService.ContainsSetting(promptedKey))
			{
				UserPrompted = true;
			}

			RunningUnderLockScreenEnabled = settingsService.GetSetting(runningEnabledKey, false);

			var frame = (PhoneApplicationFrame)Application.Current.RootVisual;
			frame.Obscured += (o, args) => RunningUnderLockScreen = args.IsLocked;
			frame.Unobscured += (o, args) => RunningUnderLockScreen = false;
		}

		bool runningUnderLockScreen;

		public bool RunningUnderLockScreen
		{
			get
			{
				return runningUnderLockScreen;
			}
			private set
			{
				Assign(() => RunningUnderLockScreen, ref runningUnderLockScreen, value);
			}
		}

		bool runningUnderLockScreenEnabled;

		public bool RunningUnderLockScreenEnabled
		{
			get
			{
				return runningUnderLockScreenEnabled;
			}
			set
			{
				AssignmentResult result = Assign(() => RunningUnderLockScreenEnabled,
								ref runningUnderLockScreenEnabled, value);

				if (result == AssignmentResult.Success)
				{
					if (runningUnderLockScreenEnabled)
					{
						PhoneApplicationService.Current.ApplicationIdleDetectionMode
															= IdleDetectionMode.Disabled;
					}
					/* Idle detection mode cannot be enabled until the application is restarted. */

					SaveSetting(runningEnabledKey, runningUnderLockScreenEnabled);
				}
			}
		}

		bool userPrompted;

		public bool UserPrompted
		{
			get
			{
				return userPrompted;
			}
			set
			{
				if (Assign(() => UserPrompted, ref userPrompted, value) == AssignmentResult.Success)
				{
					SaveSetting(promptedKey, value);
				}
			}
		}

		void SaveSetting(string key, object value)
		{
			var settingsService = Dependency.Resolve<ISettingsService, SettingsService>();
			settingsService.SetSetting(key, value);
		}
	}
}
